<template>
	<view class="uni-warp">
		<view class="example-info">
			<text class="example-info-text">为了中华民族的伟大复兴，我们要不断地提高自己，不断地塑造自己，为中华的未来出谋划策。请添加“强国”话题吧！</text>
		</view>
		<uni-section class="mb-10" title="添加话题" type="line" padding="0px 15px">
			<uni-forms ref="form" :modelValue="formData" :rules="rules" label-width="80px">
				<uni-forms-item label="选择图片" name="imgs" required>
					<uni-file-picker
						v-model="formData.imgs" 
						fileMediatype="image" 
						mode="grid" 
						limit="3"
						:auto-upload="true"
						title=" "
						@select="handleSelect"
						@delete="deleteImage"
					/> 
				</uni-forms-item>
				<uni-forms-item label="话题" name="title" required>
					<uni-easyinput v-model="formData.title" placeholder="请输入话题" />
				</uni-forms-item>
				<uni-forms-item label="话题内容" name="content" required>
					<uni-easyinput type="textarea" v-model="formData.content" placeholder="请输入话题内容" />
				</uni-forms-item>
				<button class="submit-button" @click="submitForm">提交</button>
			</uni-forms>
		</uni-section>
	</view>
</template>

<script>
export default {
	data() {
		return {
			formData: {
				title: '',
				content: '',
				imgs: []
			},
			rules: {
				title: {
					rules: [
						{
							required: true,
							errorMessage: '请输入话题',
						}
					]
				},
				content: {
					rules: [
						{
							required: true,
							errorMessage: '请输入话题内容',
						}
					]
				},
				imgs: {
					rules: [
						{
							validator: (rule, value, callback) => {
							    if (value.length === 0) {
							        callback(new Error('请至少选择一张图片'));
							    } else {
							        callback();
							    }
							}
						}
					]
				}
			}
		}
	},
	methods: {
		submitForm() {
			this.$refs.form.validate().then(res => {
				console.log('表单数据信息：', res);
				this.requestTopic(res);
			}).catch(err => {
				console.log('表单错误信息：', err);
			})
		},
		async requestTopic(formData) {
			try {
				// 这里假设你有一个全局的请求方法 $myRequest
				const res = await this.$myRequest({
					url: '/addtopic',
					method: 'POST',
					data: formData
				});
				// 请求成功后处理逻辑
				console.log('请求成功：', res);
				uni.showToast({
					title: '提交成功',
					icon: 'success'
				});
				// 清空表单
				this.formData.title = '';
				this.formData.content = '';
				this.formData.imgs = []
			} catch (err) {
				// 请求失败处理
				console.error('请求失败：', err);
				uni.showModal({
					content: '提交失败，请稍后再试',
					showCancel: false
			    });
			}
		},
		//
		//上传云空间
		async handleSelect(e) {
			for (let i in e.tempFiles) {
				try {
					const res = await uniCloud.uploadFile({
						cloudPath: `images/${Date.now()}_${e.tempFiles[i].name}`,
						filePath: e.tempFiles[i].path
					});
					console.log(res)
					this.formData.imgs.push({
						url: res.fileID,
						name: e.tempFiles[i].name
					});
				} catch(error) {
					console.log('上传失败：', error);
				}
			}
		},
		async deleteImage(e) {
		    try {
		        const fileID = this.formData.imgs[e.index].url;
				console.log('fileID:',fileID)
		        await uniCloud.deleteFile({
		            fileList: [fileID]
		        });
		        this.formData.imgs.splice(e.index, 1);
		    } catch (error) {
		        console.error('删除失败', error);
		        uni.showModal({
		            content: '删除图片失败，请稍后再试',
		            showCancel: false
		        });
		    }
		},
		async deleteImage(e) {
		    const fileID = this.formData.imgs[e.index].fileID;
		    try { // 调用云函数删除云存储文件
		        const res = await uniCloud.callFunction({
		            name: 'deleteimg',
		            data: {
		                fileID: fileID
		            }
		        });
		        if (res.result && res.result.success) {
		            console.log('云存储文件删除成功');
		            // 从本地数组中移除
		            this.formData.imgs.splice(e.index, 1);
		            uni.showToast({
		                title: '删除成功',
		                icon: 'success'
		            });
		        } else {
		            console.error('云函数删除失败', res);
		            uni.showToast({
		                title: '删除失败',
		                icon: 'none'
		            });
		        }
		    } catch (error) {
		        console.error('调用云函数出错', error);
		        uni.showToast({
		            title: '删除失败',
		            icon: 'none'
		        });
		    }
		}
	},
	mounted() {
		this.$refs.form.setRules(this.rules);
	}
}
</script>

<style lang="scss">
.example-info {
	padding: 15px;
	// background-color: #f8f9fa;
	color: #4a4c4d;
	border-radius: 8px;
	margin-bottom: 15px;
	text-align: center;
}

.submit-button {
	width: 100%;
	background-color: #007aff;
	color: white;
	border: none;
	border-radius: 8px;
	margin-top: 15px;
}
.mb-10 {
	padding: 10px 0px;
}
</style>